package com.ruoyi.system.util;

import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.utils.ReflectionUtil;
import com.ruoyi.system.domain.ColumnItems;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 开发单位：FESCO Adecco
 * 版权：FESCO Adecco
 *
 * @author：hechunbo
 * @since： JDK1.8
 * @version：1.1
 * @date：2025/8/15 最后更新日期：
 * 修改人：hechunbo
 */
public class handleExcelExport {

    public static void export(HttpServletResponse response,
                              List<?> dataList,
                              List<ColumnItems> exportFields,
                              String fileName) throws IOException {
        // 1. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=" +
                URLEncoder.encode(fileName, "UTF-8") + ".xlsx");

        // 2. 构建动态表头
        List<List<String>> head = buildDynamicHeader(exportFields);

        // 3. 构建数据
        List<List<Object>> data = buildDynamicData(dataList, exportFields);

        // 4. 使用EasyExcel导出
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .sheet("Sheet1")
                .doWrite(data);
    }

    private static List<List<String>> buildDynamicHeader(List<ColumnItems> exportFields) {
        List<List<String>> head = new ArrayList<>();
        for (ColumnItems field : exportFields) {
            head.add(Collections.singletonList(field.getDefaultLabel()));
        }
        return head;
    }

    private static List<List<Object>> buildDynamicData(List<?> dataList, List<ColumnItems> exportFields) {
        List<List<Object>> data = new ArrayList<>();
        List<String> collect = exportFields.stream().map(ColumnItems::getProp).collect(Collectors.toList());
        for (Object obj : dataList) {
            List<Object> row = new ArrayList<>();
            Map<String, Object> fieldValues = ReflectionUtil.getFieldValues(obj, collect);
            for (String field : collect) {
                row.add(fieldValues.get(field));
            }
            data.add(row);
        }
        return data;
    }
}
